<?php
/*
 * @Descripttion: 
 * @version: 
 * @Author: Eugene
 * @Date: 2023-06-20 19:55:03
 * @LastEditors 肖宇 953675853@qq.com
 * @LastEditTime 2024-09-30 10:14:16
 */

namespace app\admin\controller\tj;

use app\common\controller\Backend;
use app\common\model\shop\Ordergoods;
use think\Db;

/**
 * 产品销量
 *
 * @icon fa fa-circle-o
 */
class Sale extends Backend
{

    /**
     * Order模型对象
     * @var \app\common\model\shop\Order
     */
    protected $model = null;
    protected $acctLimit = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\shop\Order;
    }



    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        // $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if($this->auth->acct_id){
                $this->model->where('acct_id',$this->auth->acct_id);
            }
            $this->model->where('status', '>', '0');

            $filter = json_decode($this->request->get('filter'), 1);
            if ($filter && array_key_exists('time_range', $filter)) {
                // var_dump($filter);die;

                $arr = explode(' - ', $filter['time_range']);
                $this->model->where('createtime', 'between', [strtotime($arr[0]), strtotime($arr[1] . ' 23:59:59')]);
            }
            if ($filter && array_key_exists('acct_id', $filter)) {
                $this->model->where('acct_id', $filter['acct_id']);
            }
            $ids = $this->model->column('id');
            if ($ids) {
                $idstr = implode(',', $ids);
                // $list = Ordergoods::where('order_id', 'in', $ids)->join('shop_goods goods', 'ordergoods.goods_id=goods.id', 'left')->group('goods_id')->order('num desc')->field('goods.id,sum(total) as num,goods.title as name')->paginate();
                $sql = "select goods.title as name,g.goods_id as id,sum(g.total) as num from (select uw.total,uw.goods_info->'$.id' as goods_id from fa_shop_ordergoods uw where uw.order_id in ({$idstr})) g left join fa_shop_goods goods on g.goods_id=goods.id group by g.goods_id order by num desc";
                $list = Db::query($sql);
                $result = array("total" => count($list), "rows" => $list);
            } else {
                $list = [];
                $result = array("total" => 0, "rows" => []);
            }



            return json($result);
        }
        return $this->view->fetch();
    }
}
